<template>
  <div class="mapMain" id="map">
    <div class="map-con">
      <div class="map" id="mapContainer"></div>
      <div class="top"></div>
      <div class="right"></div>
      <div class="bottom"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useMassifStore } from "@/store/modules/massif";
import { useRoute, useRouter } from "vue-router";
const massifStore = useMassifStore();
const route = useRoute();
const router = useRouter();
const props = defineProps({
  listData: {
    type: Array,
    default: () => [],
  },
});
let map: any = null;
let Amaps: any = null;
onMounted(async () => {
  let AMap = await AMapLoader.load({
    key: "a29a8e74b2ea31a59623e120d41967b6", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.DistrictSearch"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  });
  map = new AMap.Map("mapContainer", {
    viewMode: "3D",
    center: [115.044141, 38.033937],
    zoom: 10,
    pitch: 30,
    zooms: [6, 16],
    features: ["bg", "road"],
  });
  map.setLayers([new AMap.TileLayer.Satellite()]);
  Amaps = AMap;

  addCity();
  addMarkers();
});

function addCity() {
  var opts = {
    subdistrict: 0,
    extensions: "all",
    level: "city",
  };
  var district = new Amaps.DistrictSearch(opts);
  district.search("晋州市", function (status: any, result: any) {
    var bounds = result.districtList[0].boundaries;
    let polygons = bounds[0].map((lin: { lng: number; lat: number }) => {
      return [lin.lng, lin.lat];
    });
    let poly = new Amaps.Polyline({
      path: polygons,
      strokeColor: "#28ebe4",
      strokeWeight: 4,
      strokeOpacity: 1,
      strokeStyle: "dashed",
    });
    map.add(poly);
  });
}

let polygons: any[] = [];
let markers: any[] = [];
function addMarkers() {
  map.remove([...markers, ...polygons]);
  polygons = [];
  markers = [];
  props.listData.forEach((mar: any) => {
    var marker = new Amaps.Marker({
      position: mar.marker,
      anchor: "bottom-center",
      content: setMarker(mar),
      offset: new Amaps.Pixel(0, -24),
    });
    marker.on("click", () => {
      openInfo(mar, marker.getPosition());
    });
    markers.push(marker);

    var polygon = new Amaps.Polygon({
      path: mar.polygon,
      strokeColor: "#00F6EF",
      strokeWeight: 2,
      strokeOpacity: 1,
      strokeStyle: "dashed",
      fillOpacity: 0.4,
      fillColor: "#125186",
      zIndex: 1000,
    });
    polygons.push(polygon);
  });

  // 将 markers 添加到地图
  map.add([...markers, ...polygons]);
  map.setFitView(markers);
}

function setMarker(mar: any) {
  return `<div class="marker" >
      <div class="marker-title">
        规模:<span class="name">${mar.area}亩</span>
      </div>
    </div>`;
}
function openInfo(mar: { scene: string }, position: any) {
  let infoWindow = new Amaps.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: setMarkerContent(mar),
    offset: new Amaps.Pixel(16, -24),
    anchor: "bottom-center",
  });
  infoWindow.open(map, position);
  infoWindow.on("click", () => {
    if (route.path == "/digit/detail") {
      router.push({ path: "/digit/vtour", query: { scene: mar.scene } });
    }
  });
  map.on("click", (e: any) => {
    infoWindow.close();
  });
}
function setMarkerContent(mar: any) {
  return `<div class="popup" >
      <div class="popup-title">
        <div class="name">编号:${mar.num}</div>
        ${
          mar.state == 0
            ? `<div class="color1">管护中</div>`
            : mar.state == 1
            ? `<div class="color2">管护中</div>`
            : `<div class="color3">已建成</div>`
        }
      </div>
      <div class="popup-con">
        <div class="detail-text">项目名称: ${mar.name}</div>
        <div class="d-ul">
          <div class="d-li">
            <div class="d-li-name">规模：</div>
            <div class="d-li-text">
              <span class="num">${mar.area}</span><span class="unit">亩</span>
            </div>
          </div>
          <div class="d-li">
            <div class="d-li-name">位置：</div>
            <div class="d-li-text">${mar.potext}</div>
          </div>
        </div>
      </div>
    </div>`;
}
watch(
  () => props.listData,
  (newVal, oldVal) => {
    console.log(newVal);
    if (oldVal) {
      addMarkers();
    }
  },
  { deep: true, immediate: true }
);
onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped lang="scss">
.mapMain {
  width: 100%;
  height: 100%;

  .map-con {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .map {
    width: 100%;
    height: 100%;
  }

  .top {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 120px;
    background: linear-gradient(
      to bottom,
      rgb(0 25 46 / 100%),
      rgb(0 25 46 / 80%),
      rgb(0 25 46 / 0%)
    );
  }

  .right {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    width: 100px;
    height: 100%;
    background: linear-gradient(to left, rgb(0 25 46 / 80%), rgb(0 25 46 / 0%));
  }

  .bottom {
    position: absolute;
    right: 0;
    bottom: 0;
    z-index: 1;
    width: 100%;
    height: 100px;
    background: linear-gradient(to top, rgb(0 25 46 / 80%), rgb(0 25 46 / 0%));
  }
}
</style>
